package cn.iocoder.yudao.module.system.service.tenant;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.institution.InstitutionPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.institution.InstitutionRespVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.institution.InstitutionSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.InstitutionDO;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.InstitutionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 机构管理 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class InstitutionServiceImpl implements InstitutionService {

    @Resource
    private InstitutionMapper institutionMapper;

    @Override
    public Long create(InstitutionSaveReqVO createReqVO) {
        // 插入
        InstitutionDO institutionDO = BeanUtils.toBean(createReqVO, InstitutionDO.class);
        institutionMapper.insert(institutionDO);
        // 返回
        return institutionDO.getId();
    }

    @Override
    public void update(InstitutionSaveReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        InstitutionDO updateObj = BeanUtils.toBean(updateReqVO, InstitutionDO.class);
        institutionMapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        institutionMapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (institutionMapper.selectById(id) == null) {
            throw exception(new ErrorCode(0, "不存在"));
        }
    }

    @Override
    public InstitutionDO get(Long id) {
        return institutionMapper.selectById(id);
    }


    @Override
    public PageResult<InstitutionDO> getPage(InstitutionPageReqVO pageReqVO) {
        return institutionMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InstitutionDO> getList(InstitutionRespVO institutionRespVO) {
        LambdaQueryWrapper<InstitutionDO> institutionDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(institutionRespVO.getName())) {
            institutionDOLambdaQueryWrapper.like(InstitutionDO::getName, institutionRespVO.getName());
        }
        return institutionMapper.selectList(institutionDOLambdaQueryWrapper);
    }

}
